package Test0301;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class CheckDemo {
    public static void main(String[] args) throws Exception {
        //1.新建测试对象
        CoculateDemo test_obj =  new CoculateDemo();
        //2.获得测试对象的Class对象
        Class<? extends CoculateDemo> coculateDemoClass = test_obj.getClass();
        //3.获取测试对象的每一个方法
        Method[] methods = coculateDemoClass.getMethods();
        //4.设置异常计数器，建立一个输出Buffer
        int num = 0;
        BufferedWriter bw  = new BufferedWriter(new FileWriter("bug.txt"));

        try {
            for (Method method : methods) {
                //5.判断这个方法是否被check标记
                if (method.isAnnotationPresent(check.class)){
                    try {
                        //执行被标记的方法
                        method.invoke(test_obj);
                    } catch (Exception e) {
                        //捕获异常，并记录到文件中
                        bw.write(method.getName()+ "方法出现异常");
                        bw.newLine();
                        bw.write("异常名称："+ e.getCause().getClass().getSimpleName());
                        bw.newLine();
                        bw.write("异常原因："+ e.getCause().getMessage());
                        bw.newLine();
                        bw.write("====================================");
                        bw.newLine();
                    }
                }
            }
            bw.write("共计"+ num +"次异常");
        } finally {
            bw.flush();
            bw.close();
        }
    }
}
